package com.tea.utils;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileUpload {
/*    private static final String RESOURCE_DIR = System.getProperty("user.dir") + "/src/main/resources";
    private static final String IMAGE_DIR = RESOURCE_DIR + "/image";
    private static final String VIDEO_DIR = RESOURCE_DIR + "/video";
    private static final String DOMAIN = "";*/

    private static final String IMAGE_DIR = "/www/wwwroot/app/file/image";
    private static final String VIDEO_DIR = "/www/wwwroot/app/file/video";
    private static final String DOMAIN = "https://cclinkhub.cn:8080";


    public static String uploadFile(MultipartFile file) throws IOException {

        String fileType = getFileType(file.getOriginalFilename());
        String targetDir;
        if ("image".equals(fileType)) {
            targetDir = IMAGE_DIR;
        } else if ("video".equals(fileType)) {
            targetDir = VIDEO_DIR;
        } else {
            throw new IllegalArgumentException("非常规图片或视频格式");
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID() + "." + getFileExtension(file.getOriginalFilename());
        Path filePath = Paths.get(targetDir, fileName);

        // 保存文件
        Files.write(filePath, file.getBytes());

        if ("image".equals(fileType)){
            return DOMAIN + "/image/" + fileName;
        }else {
            return DOMAIN + "/video/" + fileName;
        }

    }

    private static String getFileType(String fileName) {
        String extension = getFileExtension(fileName).toLowerCase();

        // 常见图片格式，包括WebP、SVG和现代格式
        if (extension.matches("(jpg|jpeg|png|gif|webp|svg|bmp|tiff|ico|avif)")) {
            return "image";
        }
        // 常见视频格式，包括流媒体和高清格式
        else if (extension.matches("(mp4|avi|mov|mkv|webm|wmv|flv|m4v|mpeg|3gp)")) {
            return "video";
        }
        // 常见音频格式
        else if (extension.matches("(mp3|wav|ogg|flac|aac|wma)")) {
            return "audio";
        }
        // 常见文档格式
        else if (extension.matches("(pdf|doc|docx|xls|xlsx|ppt|pptx|txt|rtf)")) {
            return "document";
        }
        // 常见压缩格式
        else if (extension.matches("(zip|rar|7z|gz|tar)")) {
            return "archive";
        }
        // 常见字体格式
        else if (extension.matches("(ttf|otf|woff|woff2|eot)")) {
            return "font";
        }
        return "unknown"; // 明确返回未知类型，而不是null
    }

    //获取文件拓展名
    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0) {
            return fileName.substring(dotIndex + 1);
        }
        return "";
    }
}